package com.health.trans.processor.listener;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.health.trans.kit.ThreadMonitor;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.ItemReadListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author nqlz
 */
@Slf4j
@Component
public class MyItemReadListener implements ItemReadListener {

    public static ThreadLocal<DateInfo> dateInfoLocal = new ThreadLocal<>();

    @Setter
    @Getter
    @Accessors(chain = true)
    public static class DateInfo {
        private Date start;
        private Date end;
        private Boolean isLog = false;

        public String getTime() {
            return "reader 执行时间：" + ThreadMonitor.getTime(start, end);
        }

        public void printLog() {
            if (end == null) {
                end = new Date();
            }
            log.info(getTime());
            isLog=true;
        }
    }

    @Override
    public void beforeRead() {
        if (dateInfoLocal.get() == null) {
            dateInfoLocal.set(new DateInfo().setStart(new Date()));
        }
    }

    @Override
    public void afterRead(Object o) {
        //if (dateInfoLocal.get() != null) {
        //    dateInfoLocal.get().setEnd(new Date());
        //} else {
        //    dateInfoLocal.remove();
        //    ExceptionUtil.wrapAndThrow(new RuntimeException("出错啦"));
        //}
    }

    @Override
    public void onReadError(Exception e) {
        System.out.println("reader 报错...");
    }

}
